# SERVER SETTINGS
# -----------------------------------------------------------------------------
# The base app / server logic goes all here. Before you start the server,
# please make you have renamed the file `settings.sample.coffee` to `settings.coffee`
# and properly set all specific options, especially:
#
# - Web port (default is 3456)
# - Database connection (default is MongoDB running on localhost, database "countingto").
# - Loggly domain and token (more info at http://loggly.com)
# - Debug should be disabled on production environments
#
# If you need help, check the project page at http://countingto.codeplex.com.

# Require OS to gather system info.
os = require "os"

# Get New Relic environment variables.
newRelixAppName = process.env.NEW_RELIC_APP_NAME
newRelixLicense = process.env.NEW_RELIC_LICENSE_KEY

# Check if New Relic settings are available, and if so, start the
# New Relic agent but only if not running under localhost.
if newRelixAppName? and newRelixAppName isnt "" and newRelixLicense? and newRelixLicense isnt ""
    hostname = os.hostname()
    if hostname is "localhost" or hostname.indexOf(".local") > 0
        console.log "New Relic #{newRelixAppName} won't be embedded because it's running in localhost!", hostname
    else
        console.log "Embeding New Relic agent for #{newRelixAppName}..."
        require "newrelic"

# Require internal modules.
configure = require "./server/configure.coffee"
logger = require "./server/logger.coffee"
routes = require "./server/routes.coffee"
settings = require "./server/settings.coffee"

# Log unhandled exceptions. Try using the logger, otherwise log to the console.
process.on "uncaughtException", (err) ->
    try
        logger.error "Unhandled exception!", err.stack
    catch ex
        console.error "Unhandled exception!", Date(Date.now()), err.stack

# Log proccess termination to the console.
process.on "exit", (sig) ->
    console.warn "Terminating Counting.to!", Date(Date.now()), sig

# Require express.
express = require "express"

# Create the express server.
app = express()

# Configure the server.
configure app, express

# Set routes.
routes.set app

# START
# -----------------------------------------------------------------------------
if settings.Web.ip? and settings.Web.ip isnt ""
    app.listen settings.Web.ip, settings.Web.port
else
    app.listen settings.Web.port

console.log "Counting.to app started on port #{settings.Web.port}."